﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Shared.Model;
using Client;

namespace ManageSystem.Manager
{
    public partial class FormProductDouble : UserControl
    {
        List<PRODUCT> _listProD = null;

        public FormProductDouble()
        {
            InitializeComponent();
        }

        private void buttonRefush_Click(object sender, EventArgs e)
        {
            //刷新，查询重复的MAC地址信息
            listViewProductDouble.Items.Clear();

            Task.Factory.StartNew(() =>
            {
                string sqlW = string.Format(@"YCD_MAC IN (
		SELECT
			MAC
		FROM
			(
				SELECT
					MAC,
					NODE_ID,
					COUNT (*) AS NUM
				FROM
					PROCESS
				WHERE
					NODE_ID IN ({0}, {1})
				AND END_TIME > '{2}'
				AND TEST_RESULT = 'Y'
				GROUP BY
					MAC,
					NODE_ID
				HAVING
					COUNT (MAC) >= 2
			) AS A
		GROUP BY
			MAC
		HAVING
			COUNT (*) >= 2
	)", 20063, 20064, DateTime.Now.Date.AddDays(-1));

                PRODUCT prow = new PRODUCT();
                prow.SetWhere(sqlW);

                var selectPro = MethodWcf.SelectProductClient(prow);

                //展示PRODUCT
                if (selectPro.result)
                {
                    _listProD = selectPro.value;

                    for (int i = 0; i < selectPro.value.Count; i++)
                    {
                        showProductOne(selectPro.value[i]);
                    }
                }
            });
        }

        private void showProductOne(PRODUCT product)
        {
            if (product == null) return;

            if (this.listViewProductDouble.InvokeRequired)
            {
                Action<PRODUCT> d = new Action<PRODUCT>(showProductOne);
                Invoke(d, product);
            }
            else
            {
                ListViewItem item = new ListViewItem();
                item.Text = product.ID.ToString();

                item.SubItems.Add(product.YCD_MAC);
                if (string.IsNullOrEmpty(product.MAC))
                {
                    item.SubItems.Add("");
                }
                else
                {
                    item.SubItems.Add(product.MAC);
                }

                item.SubItems.Add(product.NODE_ID.ToString());

                listViewProductDouble.Items.Add(item);
            }
        }

        private void textBoxSearch_TextChanged(object sender, EventArgs e)
        {
            //搜索
            if (_listProD == null || _listProD.Count <= 1) return;

            this.listViewProductDouble.Items.Clear();

            string value = this.textBoxSearch.Text.Trim();

            if (string.IsNullOrEmpty(value))
            {
                for (int i = 0; i < _listProD.Count; i++)
                {
                    showProductOne(_listProD[i]);
                }

                return;
            }

            var select = (from p in _listProD
                          where (p.ID + "," + p.YCD_MAC + "," + p.MAC + "," + p.NODE_ID).Contains(value)
                          select p
                        ).ToList();

            if (select != null)
            {
                for (int i = 0; i < select.Count; i++)
                {
                    showProductOne(select[i]);
                }
            }
        }

        //展示一条信息
        private void ShowProcessOne(PROCESS process)
        {
            if (process == null) return;

            if (this.listViewProcess.InvokeRequired)
            {
                Action<PROCESS> a = new Action<PROCESS>(ShowProcessOne);
                Invoke(a, process);
            }
            else
            {
                ListViewItem item = new ListViewItem();
                item.Text = process.ID.ToString();

                if (process.WORKER_ID != null)
                    item.SubItems.Add(process.STATION_ID.ToString());
                else
                    item.SubItems.Add("");

                item.SubItems.Add(process.WORKER_NAME);

                if (process.LINE_ID != null)
                    item.SubItems.Add(process.LINE_ID.ToString());
                else
                    item.SubItems.Add("");

                if (process.NODE_ID != null)
                    item.SubItems.Add(process.NODE_ID.ToString());
                else
                    item.SubItems.Add("");

                item.SubItems.Add(process.TEST_RESULT);

                if (process.START_TIME != null)
                    item.SubItems.Add(process.START_TIME.ToString());
                else
                    item.SubItems.Add("");

                if (process.END_TIME != null)
                    item.SubItems.Add(process.END_TIME.ToString());
                else
                    item.SubItems.Add("");

                this.listViewProcess.Items.Add(item);
            }
        }

        /// <summary>
        /// 展示产品信息
        /// </summary>
        /// <param name="pRODUCT"></param>
        private void ShowProductMsg(PRODUCT product, Device_Data device)
        {
            if (this.InvokeRequired)
            {
                Action<PRODUCT, Device_Data> d = new Action<PRODUCT, Device_Data>(ShowProductMsg);
                this.Invoke(d, product, device);
            }
            else
            {
                if (device != null)
                {
                    this.textBoxSn.Text = device.SN;
                    this.textBoxType.Text = device.DeviceType;
                    this.textBoxIdentify.Text = device.DeviceSerialNumber;
                    this.textBoxCode.Text = device.ProductCode;
                    this.textBoxProvince.Text = device.HW_PROVINCE_NAME;
                }

                if (product != null)
                {
                    this.textBoxYcdMac.Text = product.YCD_MAC;
                    this.textBoxProductMac.Text = product.MAC;
                    this.textBoxLineId.Text = product.LINE_ID.ToString();
                    this.textBoxNodeId.Text = product.NODE_ID.ToString();
                    this.textBoxTestResult.Text = product.TEST_RESULT;
                    this.textBoxStartTime.Text = product.START_TIME.ToString();
                    this.textBoxEndTime.Text = product.END_TIME.ToString();
                }

            }
        }

        private void listViewProductDouble_MouseClick(object sender, MouseEventArgs e)
        {
            ClearProductShow();//清空展示区域

            //找到选择好的PRODUCT
            if (listViewProductDouble.Items.Count == 0 || _listProD.Count == 0) return;
            long productId;
            if(long.TryParse(listViewProductDouble.SelectedItems[0].Text,out productId))
            {
                Task.Factory.StartNew(()=>
                {
                    ShowProductAndProcess(productId);
                });
            }
        }

        private void ShowProductAndProcess(long productId)
        {
            //展示product
            var product = (from p in _listProD
                           where productId == p.ID
                           select p).FirstOrDefault();

            if (product == null) return;

            if (string.IsNullOrEmpty(product.MAC) == false)
            {
                Device_Data deviceW = new Device_Data();
                deviceW.SetWhere();
                deviceW.MACAddr = product.MAC;
                var selectDevice = MethodWcf.SelectDeviceDataClient(deviceW);

                if (selectDevice.result)
                {
                    //展示产品信息到界面上
                    ShowProductMsg(product, selectDevice.value[0]);
                }
                else
                {
                    ShowProductMsg(product, null);
                }
            }
            else
            {
                ShowProductMsg(product, null);
            }

            //展示process

            //PROCESS按照倒叙排序
            PROCESS processW = new PROCESS();
            //processW.SetWhere();
            //processW.MAC = selectProduct.value[0].MAC;
            processW.SetWhere(string.Format("(MAC='{0}' OR MAC='{1}') ORDER BY ID DESC", product.MAC, product.YCD_MAC));

            var selectProcess = MethodWcf.SelectProcessClient(processW);

            if (selectProcess.value != null)
            {
                for(int i = 0; i < selectProcess.value.Count; i++)
                {
                    ShowProcessOne(selectProcess.value[i]);
                }
            }

        }

        //清空展示区域
        private void ClearProductShow()
        {
            if (this.InvokeRequired)
            {
                Action d = new Action(ClearProductShow);
                Invoke(d);
            }
            else
            {
                this.listViewProcess.Items.Clear();
                ClearProductMessage();
            }
        }

        //清空产品状态信息窗口
        private void ClearProductMessage()
        {
            this.textBoxSn.Clear();
            this.textBoxType.Clear();
            this.textBoxIdentify.Clear();
            this.textBoxCode.Clear();
            this.textBoxProvince.Clear();
            this.textBoxProductMac.Clear();
            this.textBoxYcdMac.Clear();
            this.textBoxLineId.Clear();
            this.textBoxNodeId.Clear();
            this.textBoxTestResult.Clear();
            this.textBoxStartTime.Clear();
            this.textBoxEndTime.Clear();
        }
    }
}
